<?php

class ExportManager {

    private $tableName;
    private $file;
    private $fields;
    private $lengths;

    public function __construct($tableID) {
        $table = new Table($tableID);
        $this->tableName = str_replace(' ', '_', trim(strtolower($table->getName())));
        $this->file = $table->getPhysicalName();

        $this->exportTable2CVS($tableID);
    }

    public function exportTable2CVS($tableID) {
        $table = new Table($tableID);
        $tableName = str_replace(' ', '_', trim(strtolower($table->getName())));
        $this->createTable($tableID, $tableName, $table->getName());
        $this->popluateTable($this->tableName, $this->fields, $this->file);
        $this->convert2CVS();
        $this->redirect2CVS();
    }

    private function createTable($tableID, $tableName, $file) {

        new Query('DROP TABLE IF EXISTS ' . $tableName);


        $queryStr = 'SELECT * FROM fields WHERE tableID = "' . $tableID . '" ORDER BY position';

        $query = new Query($queryStr);



        $createQuery = 'CREATE TABLE IF NOT EXISTS ' . $tableName . ' (ID int(25) unsigned NOT NULL auto_increment, ';
        $fields = array();
        while ($record = $query->fetchRow()) {
            $fieldName = str_replace(' ', '_', trim($record['name']));
            $fields[] = $fieldName;
            $lenghts[] = $record['length'];
            $fieldLength = $record['length'];
            $createQuery = $createQuery . ' ' . $fieldName . ' varchar( ' . $fieldLength . ' ) NOT NULL,';
        }
        $createQuery .= 'PRIMARY KEY  (ID) ) ENGINE=InnoDB;';
        new Query($createQuery);
        $this->fields = $fields;
        $this->lengths = $lenghts;
    }

    private function popluateTable($tableName, $fields, $file) {
        $inserQuery = 'INSERT INTO ' . $tableName . ' ( ' . implode(', ', $fields) . ') VALUE ';
        $inserts = array();

        $handle = fopen(DIR_DATA_RAW . DS . $file, "r") or die("Couldn't get handle");

        $lenghts = $this->lengths;

        if ($handle) {
            while (!feof($handle)) {
                $line = fgets($handle, 4096);
                if (strlen(trim($line)) == '') {
                    break;
                }
                $start = 0;
                $values = array();

                foreach ($lenghts as $length) {
                    $values[] = substr($line, $start, $length);
                    $start += $length;
                }
                $value = '("' . implode('", "', $values) . '")';
                new Query($inserQuery . $value);
            }
            fclose($handle);
        }
    }

    private function convert2CVS() {
        $output = implode(", ", $this->fields) . "\r\n";
        $handleWriter = fopen(DIR_DATA_CVS . DS . $this->file . '.cvs', "w") or die("Couldn't get handle");
        fputs($handleWriter, $output);
        $query = new Query();

        $query->select('*');
        $query->from("{$this->tableName}");
        $query->build('SELECT');
        $query->exec();

        $values = array();
        if ($handleWriter) {
            while ($record = $query->fetchRow()) {
                unset($record['ID']);
                fputs($handleWriter, implode(' ,', $record) . "\r\n");
            }
            fclose($handleWriter);
        }
    }

    private function redirect2CVS() {
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=" . $this->tableName . ".csv");
        header("Pragma: no-cache");
        header("Expires: 0");
        readfile(DIR_DATA_CVS . DS . $this->file . '.cvs');
    }

}

?>
